package com.example.captch.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captch.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private static long VILID_MILLIS_TIME = 5 * 60 * 1000;//五分钟

    @RequestMapping("/getCaptcha")
    public void genCaptcha(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());

        String code = lineCaptcha.getCode();
        System.out.println(lineCaptcha.getCode());

        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            response.setContentType("image/jpeg");
            response.setHeader("Pragma","No-cache");
            lineCaptcha.write(response.getOutputStream());
            //写入到session中
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            session.setAttribute(captchaProperties.getSession().getDate(), System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session){
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        //从session中获取
        String code = (String) session.getAttribute(captchaProperties.getSession().getCode() );
        long date = (long) session.getAttribute(captchaProperties.getSession().getDate());
        if (captcha.equalsIgnoreCase(code) && System.currentTimeMillis()-date < VILID_MILLIS_TIME){
            return true;
        }
        return false;
    }
}





















